package cloudspace.controlpanel.submitter;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.webcat.submitter.ISubmittableItem;
import org.webcat.submitter.SubmittableItemKind;

import cloudspace.vm.filesystem.CSPath;
import cloudspace.vm.filesystem.CSPathInputStream;


public class SubmittableCSPath implements ISubmittableItem
{
    public SubmittableCSPath( CSPath path )
    {
        this( null, path );
    }


    public SubmittableCSPath( SubmittableCSPath parent, CSPath path )
    {
        this.parent = parent;
        this.path = path;
    }


    public ISubmittableItem[] getChildren()
    {
        if ( getKind() == SubmittableItemKind.FOLDER )
        {
            List<CSPath> childFiles = path.getChildren();
            SubmittableCSPath[] entries = new SubmittableCSPath[childFiles.size()];

            int i = 0;
            for ( CSPath child : childFiles )
            {
                entries[i] = new SubmittableCSPath( this, child );
                i++;
            }

            return entries;
        }
        return new ISubmittableItem[0];
    }


    public String getFilename()
    {
        if ( parent == null )
        {
            return path.getName();
        }

        String parentName = parent.getFilename();

        if ( parentName.length() > 0 )
        {
            parentName = parentName + File.separator;
        }

        return parentName + path.getName();
    }


    public SubmittableItemKind getKind()
    {
        return path.isDirectory() ? SubmittableItemKind.FOLDER
            : SubmittableItemKind.FILE;
    }


    public InputStream getStream() throws IOException
    {
        if ( getKind() == SubmittableItemKind.FILE )
        {
            return new CSPathInputStream( path );
        }

        return null;
    }

    private SubmittableCSPath parent;

    private CSPath path;
}
